const { internalServerError } = require("../constant/error");
const {
  createAddress,
  findAllAddress,
  updateAddress,
  removeAddress,
  setDefaultAddr,
} = require("../service/addrService");
class AddressController {
  async create(ctx) {
    try {
      const user_id = ctx.state.user.id;
      const { consignee, phone, address } = ctx.request.body;
      const res = await createAddress({ user_id, consignee, phone, address });
      ctx.body = {
        code: 0,
        msg: "添加地址成功",
        result: res,
      };
    } catch (error) {
      console.error("添加地址失败:", error);
      ctx.app.emit("error", internalServerError, ctx, error);
    }
  }
  async findAll(ctx) {
    const user_id = ctx.state.user.id;
    const res = await findAllAddress(user_id);
    ctx.body = {
      code: 0,
      msg: "查询所有地址成功",
      result: res,
    };
  }
  async update(ctx) {
    const id = ctx.request.params.id;
    const res = await updateAddress(id, ctx.request.body);
    ctx.body = {
      code: 0,
      msg: "修改地址成功",
      result: res,
    };
  }
  async remove(ctx) {
    const id = ctx.request.params.id;
    const res = await removeAddress(id);
    ctx.body = {
      code: 0,
      msg: "删除地址成功",
      result: res,
    };
  }
  async setDefault(ctx) {
    const user_id = ctx.state.user.id;
    const id = ctx.request.params.id;
    const res = await setDefaultAddr(user_id, id);
    ctx.body = {
      code: 0,
      msg: "设为默认地址成功",
      result: res,
    };
  }
}

module.exports = new AddressController();
